const prisma = require('../utils/prisma');
const { success, error } = require('../utils/response');

/**
 * 获取订单列表
 * @route GET /api/orders
 */
const getOrders = async (req, res) => {
  try {
    const { userId, status } = req.query;
    
    // 构建查询条件
    const where = {};
    if (userId) where.userId = userId;
    if (status) where.status = status;
    
    const orders = await prisma.order.findMany({
      where,
      include: {
        user: {
          select: {
            id: true,
            name: true,
            avatar: true
          }
        }
      },
      orderBy: {
        createdAt: 'desc'
      }
    });
    
    return success(res, orders);
  } catch (err) {
    console.error('Get orders error:', err);
    return error(res, 'Failed to get orders', 500);
  }
};

/**
 * 获取今日订单
 * @route GET /api/orders/today
 */
const getTodayOrders = async (req, res) => {
  try {
    // 获取今天的日期（不包含时间）
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    // 查找今日订单
    const todayOrders = await prisma.order.findMany({
      where: {
        createdAt: {
          gte: today,
          lt: tomorrow
        }
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            avatar: true
          }
        }
      },
      orderBy: {
        createdAt: 'desc'
      }
    });
    
    return success(res, todayOrders);
  } catch (err) {
    console.error('Get today orders error:', err);
    return error(res, 'Failed to get today orders', 500);
  }
};

/**
 * 获取指定订单
 * @route GET /api/orders/:id
 */
const getOrderById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const order = await prisma.order.findUnique({
      where: { id },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            avatar: true
          }
        }
      }
    });
    
    if (!order) {
      return error(res, 'Order not found', 404);
    }
    
    return success(res, order);
  } catch (err) {
    console.error('Get order error:', err);
    return error(res, 'Failed to get order', 500);
  }
};

/**
 * 创建订单
 * @route POST /api/orders
 */
const createOrder = async (req, res) => {
  try {
    const { items, remark, diningTime } = req.body;
    const userId = req.user.id;
    
    if (!items || !Array.isArray(items) || items.length === 0) {
      return error(res, 'Order items are required', 400);
    }
    
    // 创建订单
    const order = await prisma.order.create({
      data: {
        userId,
        items: JSON.stringify(items),
        remark,
        diningTime: diningTime ? new Date(diningTime) : null,
        status: 'pending'
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            avatar: true
          }
        }
      }
    });
    
    return success(res, order, 'Order created successfully', 201);
  } catch (err) {
    console.error('Create order error:', err);
    return error(res, 'Failed to create order', 500);
  }
};

/**
 * 更新订单
 * @route PUT /api/orders/:id
 */
const updateOrder = async (req, res) => {
  try {
    const { id } = req.params;
    const { items, remark, diningTime, status } = req.body;
    
    // 检查订单是否存在
    const existingOrder = await prisma.order.findUnique({
      where: { id }
    });
    
    if (!existingOrder) {
      return error(res, 'Order not found', 404);
    }
    
    // 准备更新数据
    const updateData = {};
    
    if (items && Array.isArray(items)) updateData.items = JSON.stringify(items);
    if (remark !== undefined) updateData.remark = remark;
    if (diningTime) updateData.diningTime = new Date(diningTime);
    if (status) updateData.status = status;
    
    // 更新订单
    const updatedOrder = await prisma.order.update({
      where: { id },
      data: updateData,
      include: {
        user: {
          select: {
            id: true,
            name: true,
            avatar: true
          }
        }
      }
    });
    
    return success(res, updatedOrder, 'Order updated successfully');
  } catch (err) {
    console.error('Update order error:', err);
    return error(res, 'Failed to update order', 500);
  }
};

/**
 * 删除订单
 * @route DELETE /api/orders/:id
 */
const deleteOrder = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查订单是否存在
    const existingOrder = await prisma.order.findUnique({
      where: { id }
    });
    
    if (!existingOrder) {
      return error(res, 'Order not found', 404);
    }
    
    // 检查权限（只有管理员或订单所有者可以删除）
    if (req.user.role !== 'admin' && req.user.id !== existingOrder.userId) {
      return error(res, 'Permission denied', 403);
    }
    
    // 删除订单
    await prisma.order.delete({
      where: { id }
    });
    
    return success(res, null, 'Order deleted successfully');
  } catch (err) {
    console.error('Delete order error:', err);
    return error(res, 'Failed to delete order', 500);
  }
};

module.exports = {
  getOrders,
  getTodayOrders,
  getOrderById,
  createOrder,
  updateOrder,
  deleteOrder
};
